package com.javasm.controller;

import com.alibaba.fastjson.JSON;
import com.javasm.util.UUIDUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author WangJie
 * @version 1.0
 * @Description: 游戏列表的增删改
 * @date: 2020/7/20 16:17
 * @since JDK 1.8
 */
@WebServlet("/fileUpload")
public class FileUploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 项目所在实际路径
        String realPath = getServletContext().getRealPath("/");
        // 存放上传文件的目录
        String fileContent = "img";
//        // 使用临时文件工厂,解析文件数据
        ServletFileUpload fileUpload1 = new ServletFileUpload(new DiskFileItemFactory());
        fileUpload1.setHeaderEncoding("utf-8");// 设置中文文件上传的编码格式
        String imgSrc = "";
        Map<String, String> returnUploadInfo = new HashMap<>();
        String value = null;
        PrintWriter pw = resp.getWriter();
        try {
            List<FileItem> list = fileUpload1.parseRequest(req);
            for (FileItem fileItem : list) {
                if (!fileItem.isFormField()) {
                    // uuid重命名文件，防止同名文件被覆盖
                    String uuidName = UUIDUtil.renameUuid(fileItem.getName());
                    File file = new File(realPath + fileContent + "\\" + uuidName);
                    imgSrc = fileContent + "\\" + uuidName;
                    fileItem.write(file);
                } else {
                    //普通项，接收普通的值(表单的enctype变更，所以不能用request.getParameter())
                    String name = fileItem.getFieldName();
                    //获得普通项的值
                    value = fileItem.getString("UTF-8");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (value != null) {
            returnUploadInfo.put(value, imgSrc);
            pw.print(JSON.toJSONString(returnUploadInfo));
        } else {
            pw.print(JSON.toJSONString(imgSrc));
        }

        pw.flush();
        pw.close();


    }
}
